//
//  HTPalyer.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/31.
//

import SwiftUI
import AVKit

struct HTPalyer: UIViewControllerRepresentable {

  @Binding var var_palyer: AVPlayer
  var var_onTimeControlStatus: ((AVPlayer.TimeControlStatus) -> Void)?

  func makeUIViewController(context: UIViewControllerRepresentableContext<HTPalyer>) -> AVPlayerViewController {
    let var_vc = HTAVPlayerViewController()
    var_vc.showsPlaybackControls = false
    var_vc.var_palyer = var_palyer
    var_vc.var_onTimeControlStatus = var_onTimeControlStatus
    return var_vc
  }

  func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<HTPalyer>) {
  }
}

class HTAVPlayerViewController: AVPlayerViewController {
  var var_palyer: AVPlayer!
  var var_onTimeControlStatus: ((AVPlayer.TimeControlStatus) -> Void)?

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if var_palyer != nil {
      self.player = var_palyer
      var_palyer.addObserver(self, forKeyPath: "timeControlStatus", options: [.old, .new], context: nil)
    }
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    if (self.player != nil) {
      self.player?.pause()
      var_palyer.pause()
      var_palyer.removeObserver(self, forKeyPath: "timeControlStatus")
    }
  }

  deinit {
    print("页面销毁")
  }

  override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "timeControlStatus", let change = change, let newValue = change[NSKeyValueChangeKey.newKey] as? Int, let oldValue = change[NSKeyValueChangeKey.oldKey] as? Int {
      let var_oldStatus = AVPlayer.TimeControlStatus(rawValue: oldValue)
      let var_newStatus = AVPlayer.TimeControlStatus(rawValue: newValue)
      if var_newStatus != var_oldStatus {
        DispatchQueue.main.async {[weak self] in
          if (self != nil) {
            self!.var_onTimeControlStatus!(var_newStatus!)
          }
        }
      }
    }
  }
}
